// 引入koa-router
const Router = require('koa2-router');
const router = new Router();
// 引入model的sql语句
const {
    getStockAndSales,
    updateStockAndSales,
    addOrder,
    updateOrder,
    getOrder
} = require("../../model/api/order");
const { deleteCart } = require("../../model/api/cart");

// 引入jsonwebtoken模块
const jwt = require("jsonwebtoken");
const SECRET = "hello";

// 提交订单
router.post('/addOrder',async (ctx)=>{
    const { order,site,total } = ctx.request.body;
    const token = ctx.request.headers['authorization'];
    const decoded = jwt.verify(token, SECRET);
    /**
     * 获取当前时间戳(秒)
     */
    function getNowSceond(){
        return Math.floor(Date.now() / 1000);
    }

    /**
     * 根据时间戳获取年,月,日,时,分,秒
     * @param {*} nTimeStamps
     */
    function getTimeInfo(nTimeStamps) {
        //转毫秒
        let date = new Date(nTimeStamps * 1000);
        let month = date.getMonth() + 1;
        month = month<10?'0'+month:`${month}`;
        //返回数据
        return {
            nYear: date.getFullYear(),
            nMonth: month,
            nDay: date.getDate(),
            nHour: date.getHours(),
            nMinutes: date.getMinutes(),
            nSeconds: date.getSeconds()
        };
    }

    //当前时间戳
    let curTimeStamps = getNowSceond();
    //时间戳转对象
    let { nYear,nMonth,nDay } = getTimeInfo(curTimeStamps);

    // 生成订单编号
    let rdm = Math.floor(Math.random()*(99999-10000+1)+10000);
    // console.log(rdm);
    let order_id = nYear + nMonth + nDay + rdm;
    // console.log(order_id);

    // 商品编号
    // 商品库存减一
    let flag = true;
    JSON.parse(order).forEach((item)=>{
         (async function() {
             // 查询商品库存和销量
            let num = await getStockAndSales([item.id]);
             // console.log(num[0]);
            if (num[0].stock!==0){
                let stock = num[0].stock - item.quantity;
                let salesVolume = num[0].salesVolume + item.quantity;
                // 修改库存及销量
                await updateStockAndSales([stock,salesVolume,item.id]);
                // 订单提交成功购物车表删除对应商品
                await deleteCart([item.carid]);
            }else {
                flag = false;
            }
        })();
    })
    if (flag){
        await addOrder([order_id,decoded.ID,total,order,site.name,site.phone,site.addressProvince,site.addressCity,site.addressDistrict,site.addressDefaultAddress]);
        ctx.body = {
            code: 200,
            msg: '订单提交成功',
            order_id
        }
    }else {
        ctx.body = {
            code: 500,
            msg: '订单提交失败，商品库存不足'
        }
    }
    // console.log(ctx.request.body);
});
// 支付成功
router.post('/success',async (ctx)=>{
    let order_id = ctx.request.body.order_id;
    await updateOrder([2,order_id]);
    ctx.body = '支付成功'
});
// 订单超时
router.post('/overtime',async (ctx)=>{
    // 获取token
    const token = ctx.request.headers.authorization;
    // 解密token
    let decoded = jwt.verify(token, SECRET);

    // console.log(ctx.request.body);
    let { id } = ctx.request.body;
    // 查询
    let order = await getOrder([decoded.ID,id]);
    // console.log(order);
    let oldDate = new Date(order[0].paymenttime);
    let newDate = new Date();
    // console.log((newDate - oldDate)/1000/60/60);
    // 判断是否超时
    if ((newDate - oldDate)/1000/60/60>1){
        // 超时将当前遍历的数据状态改为4
        await updateOrder([4,order[0].orderid]);
        ctx.body = {
            code:500,
            msg: '订单已超时'
        }
    }else {
        ctx.body = {
            code:200,
            msg: 'ok'
        };
    }

})

module.exports = router;